<!-- 在帖子操作按钮部分添加收藏按钮 -->
<template>
  <div class="post-container">
    <!-- 帖子标题和内容 -->
    <div v-loading="loading" class="post-content-container">
      <h1 class="post-title">{{ post.title }}</h1>
      
      <div class="post-meta">
        <div class="author-info">
          <el-avatar :size="32" :src="post.authorAvatar || ''" />
          <span class="author-name">{{ post.authorName || '未知用户' }}</span>
          <span class="post-time">{{ formatDate(post.createdAt) }}</span>
        </div>
        
        <div class="post-category" v-if="post.categoryName">
          <el-tag size="small">{{ post.categoryName }}</el-tag>
        </div>
      </div>
      
      <div class="post-body">{{ post.content }}</div>
      
      <div class="post-tags" v-if="post.tags && post.tags.length">
        <el-tag
          v-for="(tag, index) in getPostTags(post)"
          :key="index"
          size="small"
          effect="plain"
          class="post-tag"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="post-actions">
      <el-button text @click="likePost" :loading="loading">
        <el-icon :color="post.liked ? '#409EFF' : ''"><Star /></el-icon>
        <span style="margin-left: 5px">{{ post.likes || 0 }}</span>
      </el-button>
      
      <el-button text @click="toggleFavorite" :loading="loading">
        <el-icon :color="post.favorite ? '#E6A23C' : ''">
          <Star v-if="post.favorite" />
          <StarFilled v-else />
        </el-icon>
        <span style="margin-left: 5px">{{ post.favoriteCount || 0 }}</span>
      </el-button>

      <el-button text>
        <el-icon><ChatDotSquare /></el-icon>
        <span style="margin-left: 5px">{{ post.commentCount || 0 }}</span>
      </el-button>
      
      <!-- 编辑和删除按钮 -->
      <template v-if="isAuthor || isAdmin">
        <el-button text @click="editPost" :loading="loading">
          <el-icon><Edit /></el-icon>
        </el-button>
        <el-popconfirm
          title="确定要删除这篇帖子吗？"
          @confirm="deletePost"
        >
          <template #reference>
            <el-button text :loading="loading">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-popconfirm>
      </template>
    </div>
    
    <!-- 评论区 -->
    <div class="comments-section">
      <h3>评论 ({{ post.commentCount || 0 }})</h3>
      
      <!-- 发表评论 -->
      <div class="comment-form" v-if="userInfo?.id">
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          maxlength="500"
          show-word-limit
        />
        <div class="comment-submit">
          <el-button type="primary" @click="submitComment" :loading="commentLoading">
            发表评论
          </el-button>
        </div>
      </div>
      <div v-else class="login-prompt">
        <el-alert
          title="请登录后发表评论"
          type="info"
          :closable="false"
          center
        />
      </div>
      
      <!-- 评论列表 -->
      <div class="comment-list">
        <div v-if="commentsLoading" class="loading-comments">
          <p>加载评论中...</p>
        </div>
        
        <div v-else-if="comments.length === 0" class="no-comments">
          <el-empty description="暂无评论" />
        </div>
        
        <div v-else>
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <div class="comment-user">
                <span class="username">{{ comment.authorName || '匿名用户' }}</span>
                <span v-if="comment.authorId === post.authorId" class="author-tag">作者</span>
              </div>
              <div class="comment-time">{{ formatDate(comment.createdAt) }}</div>
            </div>
            
            <div class="comment-content">{{ comment.content }}</div>
            
            <div class="comment-actions">
              <el-button 
                text 
                @click="likeComment(comment)" 
                :loading="comment.likeLoading"
              >
                <el-icon :color="comment.liked ? '#409EFF' : ''"><Star /></el-icon>
                <span style="margin-left: 5px">{{ comment.likes || 0 }}</span>
              </el-button>
              
              <el-button 
                text 
                v-if="isAdmin || userInfo.id === comment.authorId"
                @click="deleteCommentConfirm(comment)"
                :loading="comment.deleteLoading"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 加载更多 -->
          <div v-if="comments.length < post.commentCount" class="load-more">
            <el-button 
              text 
              @click="loadMoreComments" 
              :loading="commentsLoading"
            >
              加载更多
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入Element Plus图标
import { Star, StarFilled, ChatDotSquare, Edit, Delete } from '@element-plus/icons-vue';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  getPostDetail, 
  likePost as likePostAPI, 
  favoritePost, 
  unfavoritePost, 
  checkFavoriteStatus,
  deleteForumPost,
  getComments,
  getCommentsDirect,
  createComment,
  deleteComment as deleteCommentAPI,
  likeComment as likeCommentAPI,
  unlikeComment as unlikeCommentAPI
} from '@/api/forum';
import { ElMessage, ElMessageBox } from 'element-plus';

// 获取路由参数
const route = useRoute();
const router = useRouter();
const postId = computed(() => route.params.id);

// 当前用户信息
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'));
const isAdmin = computed(() => userInfo.value?.role === 'ADMIN');

// 帖子数据
const post = ref({});
const loading = ref(false);
const isAuthor = computed(() => post.value?.authorId === userInfo.value?.id);

// 评论相关
const comments = ref([]);
const commentContent = ref('');
const commentLoading = ref(false);
const commentsLoading = ref(false);
const commentPage = ref(0);
const commentSize = ref(10);

// 检查登录状态
const checkLogin = () => {
  const token = localStorage.getItem('token');
  if (!token || !userInfo.value?.id) {
    ElMessage.warning('请先登录');
    return false;
  }
  return true;
};

// 获取帖子详情
const fetchPostDetail = async () => {
  loading.value = true;
  try {
    console.log('获取帖子详情ID:', postId.value);
    const response = await getPostDetail(postId.value);
    console.log('帖子详情响应:', response);
    
    // 处理不同的响应格式：
    // 1. 直接是帖子数据对象
    // 2. 有data属性包装的对象
    // 3. 有code/data属性的标准Result对象
    if (response) {
      if (response.data) {
        // 如果包含data属性，使用data
        post.value = response.data;
      } else if (response.id) {
        // 如果不包含data但直接是帖子对象（含有id），直接使用response
        post.value = response;
      } else if (response.code && response.code === 200 && response.data) {
        // 标准Result对象
        post.value = response.data;
      } else {
        throw new Error('未识别的响应格式');
      }
      
      // 设置页面标题
      document.title = `${post.value.title || '帖子详情'} - 论坛`;
      
      // 检查收藏状态
      checkIsFavorite();
    } else {
      console.error('获取帖子详情失败：响应为空');
      ElMessage.error('获取帖子详情失败: 响应为空');
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    
    // 提供更详细的错误信息
    if (error.response) {
      console.error('错误响应状态码:', error.response.status);
      console.error('错误响应数据:', error.response.data);
      ElMessage.error(`获取帖子详情失败: ${error.response.status} - ${error.response.data?.message || '未知错误'}`);
    } else if (error.request) {
      console.error('未收到响应', error.request);
      ElMessage.error('获取帖子详情失败: 服务器未响应');
    } else {
      console.error('请求配置错误', error.message);
      ElMessage.error(`获取帖子详情失败: ${error.message}`);
    }
  } finally {
    loading.value = false;
  }
};

// 点赞帖子
const likePost = async () => {
  if (!checkLogin()) return;
  
  try {
    await likePostAPI(postId.value);
    // 更新点赞状态
    post.value.liked = !post.value.liked;
    if (post.value.liked) {
      post.value.likes = (post.value.likes || 0) + 1;
    } else {
      post.value.likes = Math.max(0, (post.value.likes || 1) - 1);
    }
    ElMessage.success(post.value.liked ? '点赞成功' : '取消点赞成功');
  } catch (error) {
    console.error('点赞操作失败:', error);
    ElMessage.error('点赞操作失败: ' + error.message);
  }
};

// 检查收藏状态
const checkIsFavorite = async () => {
  if (!userInfo.value?.id) return;
  
  try {
    const response = await checkFavoriteStatus(postId.value);
    if (response && response.data) {
      post.value.favorite = response.data.favorite || false;
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error);
  }
};

// 切换收藏状态
const toggleFavorite = async () => {
  if (!checkLogin()) return;
  
  try {
    if (post.value.favorite) {
      await unfavoritePost(postId.value);
      post.value.favoriteCount = Math.max(0, (post.value.favoriteCount || 1) - 1);
    } else {
      await favoritePost(postId.value);
      post.value.favoriteCount = (post.value.favoriteCount || 0) + 1;
    }
    post.value.favorite = !post.value.favorite;
    ElMessage.success(post.value.favorite ? '收藏成功' : '取消收藏成功');
  } catch (error) {
    console.error('收藏操作失败:', error);
    ElMessage.error('收藏操作失败: ' + error.message);
  }
};

// 编辑帖子
const editPost = () => {
  if (!checkLogin()) return;
  
  // 实现编辑帖子功能
  router.push(`/forum/edit/${postId.value}`);
};

// 删除帖子
const deletePost = async () => {
  if (!checkLogin()) return;
  
  try {
    // 确认删除
    await ElMessageBox.confirm(
      '确定要删除这篇帖子吗？删除后不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 实现删除帖子功能
    await deleteForumPost(postId.value);
    ElMessage.success('删除成功');
    router.push('/forum');
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不显示错误
      return;
    }
    console.error('删除帖子失败:', error);
    ElMessage.error('删除帖子失败: ' + error.message);
  }
};

// 获取评论列表
const fetchComments = async (page = 0, append = false) => {
  commentsLoading.value = true;
  try {
    let response;
    let fetchedComments = [];
    
    // 首先尝试使用直接获取评论的方法
    if (page === 0 && !append) {
      try {
        const directResponse = await getCommentsDirect(postId.value);
        
        // 检查是否获取到了评论数据
        if (directResponse) {
          if (Array.isArray(directResponse) && directResponse.length > 0) {
            fetchedComments = directResponse;
            
            // 提前返回，避免继续执行不必要的查询
            if (fetchedComments.length > 0) {
              const processedComments = fetchedComments.map(comment => ({
                ...comment,
                likeLoading: false,
                deleteLoading: false
              }));
              
              comments.value = processedComments;
              
              // 更新本地的评论计数，确保UI一致
              if (post.value) {
                post.value.commentCount = fetchedComments.length;
              }
              
              commentsLoading.value = false;
              return; // 提前返回，不再处理后续代码
            }
          } else if (directResponse.content && Array.isArray(directResponse.content) && directResponse.content.length > 0) {
            // 检查是否是Spring Data Page格式
            fetchedComments = directResponse.content;
          }
        }
        
        // 如果直接获取方法没有立即返回，则尝试分页方法
        if (fetchedComments.length === 0) {
          response = await getComments(postId.value, {
            page,
            size: commentSize.value
          });
        }
      } catch (directError) {
        console.error('直接获取评论失败:', directError);
        // 如果直接获取失败，回退到分页方法
        response = await getComments(postId.value, {
          page,
          size: commentSize.value
        });
      }
    } else {
      // 对于分页请求，使用常规分页API
      response = await getComments(postId.value, {
        page,
        size: commentSize.value
      });
    }
    
    // 如果还没有评论数据，并且有response，则处理response
    if (fetchedComments.length === 0 && response) {
      if (response.data) {
        // 检查各种可能的响应格式
        if (Array.isArray(response.data)) {
          fetchedComments = response.data;
        } else if (response.data.content && Array.isArray(response.data.content)) {
          fetchedComments = response.data.content;
        } else if (typeof response.data === 'object' && 
                  response.data.pageable && 
                  response.data.totalElements !== undefined && 
                  response.data.content) {
          fetchedComments = response.data.content;
        } else {
          // 最后尝试查找任何数组
          for (const key in response.data) {
            if (Array.isArray(response.data[key])) {
              fetchedComments = response.data[key];
              break;
            }
          }
        }
      }
    }
    
    if (fetchedComments.length > 0) {
      // 添加标志位
      const processedComments = fetchedComments.map(comment => ({
        ...comment,
        likeLoading: false,
        deleteLoading: false
      }));
      
      if (append) {
        comments.value = [...comments.value, ...processedComments];
      } else {
        comments.value = processedComments;
      }
      
      // 更新本地的评论计数，确保UI一致
      if (!append && post.value) {
        const totalElements = response?.data?.totalElements;
        post.value.commentCount = totalElements !== undefined ? totalElements : fetchedComments.length;
      }
    } else {
      if (!append) {
        comments.value = [];
      }
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    // 评论加载失败不应该影响帖子详情的显示
    if (!append) {
      comments.value = [];
    }
  } finally {
    commentsLoading.value = false;
  }
};

// 加载更多评论
const loadMoreComments = () => {
  commentPage.value += 1;
  fetchComments(commentPage.value, true);
};

// 提交评论
const submitComment = async () => {
  if (!checkLogin()) return;
  
  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }
  
  commentLoading.value = true;
  try {
    await createComment(postId.value, {
      content: commentContent.value.trim()
    });
    
    ElMessage.success('评论发表成功');
    commentContent.value = '';
    
    // 重新获取帖子详情和评论
    fetchPostDetail();
    fetchComments();
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('发表评论失败: ' + error.message);
  } finally {
    commentLoading.value = false;
  }
};

// 点赞评论
const likeComment = async (comment) => {
  if (!checkLogin()) return;
  
  comment.likeLoading = true;
  try {
    if (comment.liked) {
      await unlikeCommentAPI(comment.id);
      comment.likes = Math.max(0, comment.likes - 1);
    } else {
      await likeCommentAPI(comment.id);
      comment.likes = (comment.likes || 0) + 1;
    }
    comment.liked = !comment.liked;
  } catch (error) {
    console.error('评论点赞操作失败:', error);
    ElMessage.error('点赞操作失败: ' + error.message);
  } finally {
    comment.likeLoading = false;
  }
};

// 确认删除评论
const deleteCommentConfirm = (comment) => {
  ElMessageBox.confirm(
    '确定要删除该评论吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteCommentAction(comment);
  }).catch(() => {
    // 用户取消，不做处理
  });
};

// 删除评论
const deleteCommentAction = async (comment) => {
  if (!comment || !comment.id) {
    ElMessage.error('评论数据不完整，无法删除');
    return;
  }
  
  comment.deleteLoading = true;
  try {
    console.log('开始删除评论:', comment);
    await deleteCommentAPI(postId.value, comment.id);
    ElMessage.success('评论已删除');
    
    // 从当前列表中移除
    comments.value = comments.value.filter(c => c.id !== comment.id);
    
    // 更新评论计数
    if (post.value.commentCount) {
      post.value.commentCount -= 1;
    }
  } catch (error) {
    console.error('删除评论失败:', error);
    ElMessage.error('删除评论失败: ' + (error.message || '未知错误'));
  } finally {
    comment.deleteLoading = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化短日期 (只显示年月日)
const formatShortDate = (dateString) => {
  if (!dateString) return '';
  
  // 处理不同格式的日期字符串
  let date;
  if (typeof dateString === 'string') {
    // 如果是ISO日期字符串
    if (dateString.includes('T')) {
      date = new Date(dateString);
    } 
    // 如果是YYYY-MM-DD格式
    else if (dateString.includes('-') && dateString.length >= 10) {
      const parts = dateString.split('-');
      date = new Date(parts[0], parts[1] - 1, parts[2]);
    } 
    // 尝试直接解析
    else {
      date = new Date(dateString);
    }
  } else if (dateString instanceof Date) {
    date = dateString;
  } else {
    return '';
  }
  
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取帖子标签
const getPostTags = (post) => {
  if (!post.tags) return [];
  
  if (typeof post.tags === 'string') {
    return post.tags.split(/[,，\s]+/).filter(tag => tag.trim() !== '');
  }
  
  return post.tags;
};

// 页面加载时获取帖子详情和评论
onMounted(() => {
  fetchPostDetail();
  fetchComments();
});

// 带重试的评论获取
const fetchCommentsWithRetry = async (maxRetries = 2) => {
  let retries = 0;
  let success = false;
  
  const tryFetchComments = async () => {
    await fetchComments();
    // 检查是否获取到评论
    if (comments.value.length > 0) {
      console.log('成功获取到评论数据，无需重试');
      success = true;
      return;
    }
    
    // 如果没有获取到评论，并且还有重试次数，则延迟后重试
    if (retries < maxRetries) {
      retries++;
      console.log(`未获取到评论数据，${retries}秒后重试(${retries}/${maxRetries})...`);
      await new Promise(resolve => setTimeout(resolve, retries * 1000));
      await tryFetchComments();
    } else if (!success) {
      console.warn('多次尝试后仍未获取到评论数据');
    }
  };
  
  await tryFetchComments();
};
</script>

<style scoped>
.post-container {
  padding: 20px;
}

.post-content-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-title {
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 16px;
  color: #303133;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-size: 14px;
  color: #606266;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-weight: bold;
  margin-right: 8px;
}

.post-time {
  color: #909399;
}

.post-body {
  font-size: 16px;
  line-height: 1.8;
  margin-bottom: 24px;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.post-actions {
  display: flex;
  gap: 10px;
  margin: 15px 0;
}

.comments-section {
  margin-top: 30px;
  border-top: 1px solid #e0e0e0;
  padding-top: 20px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-submit {
  margin-top: 10px;
  text-align: right;
}

.login-prompt {
  margin-bottom: 20px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.comment-user {
  display: flex;
  align-items: center;
}

.username {
  font-weight: bold;
  margin-right: 8px;
}

.author-tag {
  background-color: #409EFF;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.comment-time {
  color: #909399;
  font-size: 14px;
}

.comment-content {
  line-height: 1.6;
  margin-bottom: 10px;
  word-break: break-all;
}

.comment-actions {
  display: flex;
  justify-content: flex-start;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.no-comments {
  padding: 20px 0;
}

.loading-comments {
  padding: 10px;
  background-color: #f0f0f0;
  margin-bottom: 20px;
}
</style> 